import os
from PIL import Image
from PIL.ExifTags import TAGS, GPSTAGS
from docx import Document
from docx.shared import Inches

def get_exif_data(image_path):
    """提取图片的 EXIF 信息"""
    try:
        image = Image.open(image_path)
        exif_data = image._getexif()
        if not exif_data:
            return None
        gps_info = {}
        for tag, value in exif_data.items():
            tag_name = TAGS.get(tag, tag)
            if tag_name == "GPSInfo":
                for key in value.keys():
                    gps_tag = GPSTAGS.get(key, key)
                    gps_info[gps_tag] = value[key]
        return gps_info
    except Exception as e:
        print(f"无法读取图片 {image_path} 的 EXIF 信息: {e}")
        return None

def get_coordinates(gps_info):
    """从 GPS 信息中提取经纬度"""
    def convert_to_degrees(value):
        d, m, s = value
        return d + (m / 60.0) + (s / 3600.0)

    if not gps_info:
        return None, None

    lat = gps_info.get("GPSLatitude")
    lat_ref = gps_info.get("GPSLatitudeRef")
    lon = gps_info.get("GPSLongitude")
    lon_ref = gps_info.get("GPSLongitudeRef")

    if lat and lat_ref and lon and lon_ref:
        latitude = convert_to_degrees(lat)
        if lat_ref != "N":
            latitude = -latitude

        longitude = convert_to_degrees(lon)
        if lon_ref != "E":
            longitude = -longitude

        return longitude, latitude
    return None, None

def validate_image(image_path):
    """验证图片是否有效"""
    try:
        with Image.open(image_path) as img:
            img.verify()  # 验证图片文件是否有效
        return True
    except Exception as e:
        print(f"无效的图片文件 {image_path}: {e}")
        return False

def resize_image(image_path, max_width=2400):
    """调整图片大小以适应文档"""
    try:
        with Image.open(image_path) as img:
            if img.width > max_width:
                ratio = max_width / float(img.width)
                new_height = int(img.height * ratio)
                resized_img = img.resize((max_width, new_height))
                temp_path = f"{image_path}_resized.jpg"
                resized_img.save(temp_path, "JPEG")
                return temp_path
        return image_path
    except Exception as e:
        print(f"无法调整图片大小 {image_path}: {e}")
        return image_path

def generate_docx(image_data, output_path):
    """生成 .docx 文件并插入图片"""
    document = Document()
    for longitude, latitude, image_path in image_data:
        try:
            document.add_paragraph(f"经度: {longitude:.6f}  纬度: {latitude:.6f}")
            resized_image_path = resize_image(image_path)  # 调整图片大小
            document.add_picture(resized_image_path, )  # 插入图片
            if resized_image_path != image_path:
                os.remove(resized_image_path)  # 删除临时调整大小的图片
        except Exception as e:
            print(f"无法将图片 {image_path} 插入文档: {e}")
    document.save(output_path)

def process_images(folder_path, output_path):
    """主流程：读取图片、提取 EXIF 信息并生成 .docx"""
    image_data = []
    for file_name in os.listdir(folder_path):
        file_path = os.path.join(folder_path, file_name)
        if file_name.lower().endswith(('.jpg', '.jpeg', '.png')):
            if validate_image(file_path):  # 验证图片是否有效
                gps_info = get_exif_data(file_path)
                longitude, latitude = get_coordinates(gps_info)
                if longitude is not None and latitude is not None:
                    image_data.append((longitude, latitude, file_path))
    generate_docx(image_data, output_path)

# 示例调用
if __name__ == "__main__":
    folder_path = "/app/input"
    output_path = "/app/output/output.docx"  # 输出的 .docx 文件路径
    process_images(folder_path, output_path)